<div class="pure-form">
  <input id="new_name" type="text" placeholder="{New Page}" onkeypress="if(event.which == 13) add_page();">
  <button type="submit" class="pure-button pure-button-primary" onclick="add_page();">Instant Add</button>
  <button class="pure-button pure-button-new" onclick="$.blockUI();location.href = __install_url + '?d=' + __dir + '&f=index_page' + '&sys=' + __data[0].id;">Add</button>
  <button class="pure-button pure-button-preview" onclick="window.open(__home_url + __data[0].php_name + '.php');">Preview</button>
</div>
<div class="dd" id="nestable3"></div>

<div id="dialog_change" class="pure-form" style="display: none;" title="Change Name">
  <input type="text" id="name_change" style="width: 100%;"></input>
</div>

<script type="text/javascript">
  var __prev_ajax;
  
  function init_pages() {
    set_pages();
  }

  function set_pages() {
    var elm;
    $('#nestable3').empty();
    $('#nestable3').append('<ol id="pgol_' + __root.id + '"  class="dd-list"></ol>');
    __set_pages(__root, $('#pgol_' + __root.id));
    
    var func = function(e) {
      if (e.target.id == 'nestable3') {
        update_changes();
      }
    };
    
    // activate Nestable for list 1
    $('#nestable3').nestable({
      maxDepth: 99
    }).on('change', func);

    set_logins();
  }

  function __set_pages(node, elm) {
    for (var idx in node.__c) {
      var itm = node.__c[idx];
      elm.append('<li class="dd-item dd3-item" data-id="' + itm.id + '" data-name="' + itm.name + '" data-parent_id="' + itm.parent_id + '" data-order="' + itm.name + '" data-is_default="' + itm.is_default + '" data-is_visible="' + itm.is_visible + '" data-sys_id="' + itm.sys_id + '">' +
                   '<div class="dd-handle dd3-handle">&nbsp;</div>' +
                   '<div class="dd3-content">' +
                     '<a href="#" onclick="change_name(' + itm.id + ', \'' +  itm.name + '\', event);">' + itm.name + '</a>' +
                     '<span class="ui-button-icon-primary ui-icon ui-icon-closethick" onclick="delete_page(' + itm.id +', ' + itm.is_default + ')"></span>' + 
                     '<span class="ui-button-icon-primary ui-icon ui-icon-folder-collapsed" onclick="$.blockUI();location.href = \'' + __install_url + '?d=' + __dir + '&f=index_page&sys=' + __data[0].id + '&pg=' + itm.id + '\';"></span>' + 
                     '<input type="checkbox" ' + ((itm.is_visible == 1) ? 'checked="checked"' : '') + ' onclick="set_visible(' + itm.id + ', this.checked ? 1 : 0);"></input>' + 
                     '<input type="radio" ' + ((itm.is_default == 1) ? 'checked="checked"' : '') + ' name="homepage"' + ' onclick="set_homepage(' + itm.id + ');"></input>' + 
                   '</div>' + 
                   ((itm.__c.length > 0) ? '<ol id="pgol_' + itm.id + '"  class="dd-list"></ol>' : '') + 
                 '</li>');
      if (itm.__c.length > 0) {
        __set_pages(itm, $('#pgol_' + itm.id));
      }
    }
  }

 
  function update_changes() {
    if (__prev_ajax) {
      __prev_ajax.abort();
    }
    var new_pages = Utils.get_array($('#nestable3').nestable('serialize'), 0);
    var reqs = [];
    for (var idx in new_pages) {
      var itm = new_pages[idx];
      reqs.push({
        id: itm.id,
        parent_id: itm.parent_id,
        order: itm.order
      });
    }
    __prev_ajax = Ajax.request(
      'firewall.php?d=' + __dir + '&f=' + __file + '&m=update_pages',
      'reqs=' + Utils.encodeURI(JSON.stringify(reqs)),
      function(rslt) {
        __pages = new_pages;
        __root = Utils.get_root(__pages);
      },
      { silent: 1 }
    );
  }


  function set_visible(page_id, is_visible) {
    var req = Utils.get_by_id(page_id, __pages);
    req.is_visible = is_visible;
    Ajax.request(
      'firewall.php?d=' + __dir + '&f=' + __file + '&m=update_pages',
      'reqs=' + Utils.encodeURI(JSON.stringify([ req ])),
      function(rslt) {
        __root = Utils.get_root(__pages);
        set_pages();
      },
      null
    );
  }

  function set_homepage(page_id) {
    for (var idx in __pages) {
      var itm = __pages[idx];
      itm.is_default = 0;
    }
    var req = Utils.get_by_id(page_id, __pages);
    req.is_default = 1;
    Ajax.request(
      'firewall.php?d=' + __dir + '&f=' + __file + '&m=update_pages',
      'reqs=' + Utils.encodeURI(JSON.stringify([ req ])),
      function(rslt) {
        __root = Utils.get_root(__pages);
        set_pages();
      },
      null
    );
  }

  function delete_page(page_id, is_default) {
    var req = Utils.get_by_id(page_id, __pages);
    Ajax.request(
      'firewall.php?d=' + __dir + '&f=' + __file + '&m=delete_page',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        __root = Utils.get_root(__pages);
        set_pages();
      },
      { confirm: 1 }
    );
  }

  function add_page() {
    var req = {
      name: $("#new_name")[0].value,
      sys_id: __data[0].id,
      parent_id: 0,
      is_default: (__pages.length > 0) ? 0 : 1,
      is_visible: 1,
      html: '',
      js: '',
      css: '',
      icon: ''
    };
    Ajax.request(
      'firewall.php?d=' + __dir + '&f=index_page&m=submit_page',
      'req=' + Utils.encodeURI(JSON.stringify(req)),
      function(rslt) {
        $("#new_name")[0].value = '';
        __pages.push(rslt);
        __root = Utils.get_root(__pages);
        set_pages();
      },
      null
    );
  }

  function change_name(id, name, ev) {
    var func = function() {
      var req = {
        id: id,
        name: $('#name_change')[0].value
      };
      Ajax.request(
        'firewall.php?d=' + __dir + '&f=index_page&m=submit_page',
        'req=' + Utils.encodeURI(JSON.stringify(req)),
        function(rslt) {
          for (var idx in __pages) {
            var itm = __pages[idx];
            if (itm.id == id) {
              itm.name = $('#name_change')[0].value;
            }
          }
          __root = Utils.get_root(__pages);
          set_pages();
          $('#dialog_change').dialog('close');
        },
        null
      );
    };
    
    $('#dialog_change').dialog({
      position: {
        my: 'left+0 bottom+0',
        of: ev.target
      },
      buttons: {
        'OK': function() {
          func();
        },
        'Cancel': function() { 
          $(this).dialog('close');
        }
      }
    });

    $('#name_change')[0].onkeypress = function(ev) {
      if(ev.which == 13) {
        func();
      }
    };
    $('#name_change')[0].value = name;
    $('#name_change').select();
  }
</script>
